<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_commit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="applyTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:admCarDriveRecord:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate(any)" v-hasPermi="['system:admCarDriveRecord:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:admCarDriveRecord:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:admCarDriveRecord:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

     <el-table v-loading="loading" :data="admCarDriveRecordList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 车牌号 -->
      <el-table-column label="车牌号" align="center">
        <template #default="scope">
          <span>{{ scope.row.carName || '未知车牌' }}</span>
        </template>
      </el-table-column>
      <!-- 总费用 -->
      <el-table-column label="总费用(元)" align="center">
        <template #default="scope">
          <span>{{ scope.row.amountAll || 0 }}</span>
        </template>
      </el-table-column>
      <!-- 创建时间 -->
      <el-table-column label="创建时间" align="center" width="180">
        <template #default="scope">
          <span>{{ scope.row.createTime ? dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}</span>
        </template>
      </el-table-column>
      <!-- 审批状态 -->
      <el-table-column label="审批状态" align="center">
        <template #default="scope">
          <dict-tag :options="approval_commit_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
          </el-tooltip>
          <!-- 审批按钮 -->
            <el-tooltip content="提交审批" placement="top">
              <el-button
                link
                type="primary"
                icon="DocumentChecked"
                @click="openApprovalFlow(scope.row)"
              ></el-button>
            </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      title="车辆行驶记录申请"
      width="1400px"
      append-to-body
      :before-close="cancel"
    >
      <!-- 筛选表单 -->
      <el-form ref="filterFormRef" :model="form" label-width="100px" label-position="left" style="padding: 20px 24px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录人" prop="recordName">
              <el-input v-model="form.recordName" placeholder="请输入记录人" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptTree"
                placeholder="请选择部门"
                :props="{ label: 'label', value: 'id', children: 'children' }"
                check-strictly
                filterable
                :default-expand-all="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆选择">
              <el-select v-model="form.carId" @change="onCarChange" placeholder="请选择车辆" filterable>
                <el-option
                  v-for="car in carList"
                  :key="car.id"
                  :label="`${car.model} (${car.carNumber})`"
                  :value="car.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 表格上方左上角按钮 -->
      <div style="margin: 10px 0; display: flex; gap: 10px;">
        <el-button type="primary" @click="addTrip" text>新增行程</el-button>
        <el-button type="danger" @click="removeSelectedTrips" :disabled="!selectedTrips.length" text>删除选中</el-button>
      </div>

      <!-- 车辆行驶记录表格 -->
      <el-table
        border
        :data="applications"
        v-model:selection="selectedTrips"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <!-- 报销状态列 -->
        <el-table-column prop="reimbursementStatus" label="报销状态" width="120">
          <template #default="{ row }">
            <el-tooltip :content="String(mapReimbursementStatus(row.reimbursementStatus))" effect="dark">
              <span>{{ mapReimbursementStatus(row.reimbursementStatus) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 使用人 -->
        <el-table-column prop="usageName" label="使用人" width="120">
          <template #default="{ row }">
            <el-tooltip :content="row.usageName || '点击选择人员'" effect="dark">
              <div class="editable-cell" @click="openUserSelector(row, 'usage')">
                {{ row.usageName || '点击选择人员' }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 使用日期 -->
        <el-table-column prop="usageTime" label="使用日期" width="120">
          <template #default="{ row }">
            <div v-if="!row.editing?.usageTime">
              <el-tooltip :content="row.usageTime || '点击选择日期'" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, usageTime: true }">
                  {{ row.usageTime || '点击选择日期' }}
                </div>
              </el-tooltip>
            </div>
            <el-date-picker
              v-else
              v-model="row.usageTime"
              type="date"
              value-format="YYYY-MM-DD"
              size="small"
              @blur="row.editing.usageTime = false"
            />
          </template>
        </el-table-column>

        <!-- 出发地点 -->
        <el-table-column prop="departurePlace" label="出发地点" width="120">
          <template #default="{ row }">
            <div v-if="!row.editing?.departurePlace">
              <el-tooltip :content="row.departurePlace || '点击输入'" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, departurePlace: true }">
                  {{ row.departurePlace || '点击输入' }}
                </div>
              </el-tooltip>
            </div>
            <el-input
              v-else
              v-model="row.departurePlace"
              size="small"
              @blur="row.editing.departurePlace = false"
              @keyup.enter="row.editing.departurePlace = false"
            />
          </template>
        </el-table-column>

        <!-- 目的地 -->
        <el-table-column prop="destination" label="目的地" width="120">
          <template #default="{ row }">
            <div v-if="!row.editing?.destination">
              <el-tooltip :content="row.destination || '点击输入'" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, destination: true }">
                  {{ row.destination || '点击输入' }}
                </div>
              </el-tooltip>
            </div>
            <el-input
              v-else
              v-model="row.destination"
              size="small"
              @blur="row.editing.destination = false"
              @keyup.enter="row.editing.destination = false"
            />
          </template>
        </el-table-column>

        <el-table-column prop="projectIds" label="项目名称" width="250">
          <template #default="{ row }">
            <div v-if="!row.editing?.projectIds" class="project-name-cell">
              <el-tooltip :content="row.projectName || '点击选择项目'" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, projectIds: true }">
                  <span class="text-ellipsis">
                    {{ row.projectName || '点击选择项目' }}
                  </span>
                </div>
              </el-tooltip>
            </div>
            <el-select
              v-else
              v-model="row.projectIds"
              multiple
              placeholder="请输入项目名称搜索"
              clearable
              filterable
              remote
              reserve-keyword
              :remote-method="(query) => queryProjectListForRow(query, row)"
              :loading="projectLoading"
              size="small"
              style="width: 100%"
              @change="val => handleProjectChange(row, val)"
              @blur="row.editing.projectIds = false"
              :value-key="'id'"
            >
              <el-option
                v-for="project in row.projectList || []"
                :key="project.id"
                :label="`${project.proName} (${project.proNumber || ''})`"
                :value="project.id"
              />
            </el-select>
          </template>
        </el-table-column>

        <!-- 随行人员 -->
        <el-table-column prop="entourageName" label="随行人员" width="120">
          <template #default="{ row }">
            <el-tooltip :content="row.entourageName || '点击选择人员'" effect="dark">
              <div class="editable-cell" @click="openUserSelector(row, 'entourage')">
                {{ row.entourageName || '点击选择人员' }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 用车时间列 -->
        <el-table-column prop="useTime" label="用车时间" width="120">
          <template #default="{ row }">
            <el-tooltip :content="row.useTime || '点击选择'" effect="dark">
              <div v-if="row.readonly">{{ row.useTime || '-' }}</div>
              <div v-else>
                <div v-if="!row.editing?.useTime" class="editable-cell" @click="row.editing = { ...row.editing, useTime: true }">
                  {{ row.useTime || '点击选择' }}
                </div>
                <el-date-picker
                  v-else
                  v-model="row.useTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  size="small"
                  :picker-options="{ disabledDate: date => row.backTime && date > new Date(row.backTime) }"
                  @change="() => onUseTimeChange(row)"
                  @blur="row.editing.useTime = false"
                />
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 返回时间 -->
        <el-table-column prop="backTime" label="返回时间" width="120">
          <template #default="{ row }">
            <div v-if="!row.editing?.backTime">
              <el-tooltip :content="row.backTime || '点击选择'" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, backTime: true }">
                  {{ row.backTime || '点击选择' }}
                </div>
              </el-tooltip>
            </div>
            <el-date-picker
              v-else
              v-model="row.backTime"
              type="date"
              value-format="YYYY-MM-DD"
              size="small"
              :picker-options="{ disabledDate: date => row.useTime && date < new Date(row.useTime) }"
              @change="() => onBackTimeChange(row)"
              @blur="row.editing.backTime = false"
            />
          </template>
        </el-table-column>

        <!-- 起始里程 -->
        <el-table-column prop="startMileage" label="起始里程" width="120">
          <template #default="{ row }">
            <div v-if="!row.editing?.startMileage">
              <el-tooltip :content="String(row.startMileage ?? '')" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, startMileage: true }">
                  {{ row.startMileage ?? '点击输入' }}
                </div>
              </el-tooltip>
            </div>
            <el-input
              v-else
              v-model="row.startMileage"
              size="small"
              placeholder="请输入数字"
              @input="formatNumberInput(row, 'startMileage')"
              @change="val => onStartMileageChange(row, val)"
            />
          </template>
        </el-table-column>

        <!-- 终止里程 -->
        <el-table-column prop="endMileage" label="终止里程" width="120">
          <template #default="{ row }">
            <div v-if="!row.editing?.endMileage">
              <el-tooltip :content="String(row.endMileage ?? '')" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, endMileage: true }">
                  {{ row.endMileage ?? '点击输入' }}
                </div>
              </el-tooltip>
            </div>
            <el-input
              v-else
              v-model="row.endMileage"
              size="small"
              placeholder="请输入数字"
              @input="formatNumberInput(row, 'endMileage')"
              @change="val => onEndMileageChange(row, val)"
            />
          </template>
        </el-table-column>

        <!-- 里程数（只显示） -->
        <el-table-column prop="mileageNumber" label="里程数" width="120">
          <template #default="{ row }">
            <el-tooltip :content="String(row.mileageNumber ?? 0)" effect="dark">
              {{ row.mileageNumber ?? 0 }}
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 费用列 -->
        <el-table-column
          v-for="prop in [
            'toll', 'fuelCost', 'oilConsumption', 'oilPrice',
            'postageSubsidy', 'parkFree', 'rentalFree', 'maintenanceCost', 'otherExpenses'
          ]"
          :key="prop"
          :prop="prop"
          :label="getFeeLabel(prop)"
          width="120"
        >
          <template #default="{ row }">
            <div v-if="!row.editing?.[prop]">
              <el-tooltip :content="String(row[prop] ?? 0)" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, [prop]: true }">
                  {{ row[prop] ?? 0 }}
                </div>
              </el-tooltip>
            </div>
            <el-input
              v-else
              v-model="row[prop]"
              size="small"
              placeholder="请输入数字"
              @input="formatNumberInput(row, prop)"
              @blur="row.editing[prop] = false; computeAmountAll(row)"
            />
          </template>
        </el-table-column>

        <!-- 总费用 -->
        <el-table-column prop="amountAll" label="总费用(元)" width="120">
          <template #default="{ row }">
            <el-tooltip :content="String(row.amountAll ?? 0)" effect="dark">
              {{ row.amountAll ?? 0 }}
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 附件上传 -->
        <el-table-column prop="attachmentName" label="附件上传" width="150">
          <template #default="{ row }">
            <el-button type="text" @click="handleAttachmentUpload(row, 2)">
              {{ row.attachmentName || '点击上传' }}
            </el-button>
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column prop="remark" label="备注" width="200">
          <template #default="{ row }">
            <div v-if="!row.editing?.remark">
              <el-tooltip :content="row.remark || '点击输入备注'" effect="dark">
                <div class="editable-cell" @click="row.editing = { ...row.editing, remark: true }">
                  {{ row.remark || '点击输入备注' }}
                </div>
              </el-tooltip>
            </div>
            <el-input
              v-else
              type="textarea"
              :rows="2"
              v-model="row.remark"
              size="small"
              @blur="row.editing.remark = false"
            />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitAll">提交</el-button>
      </template>
    </el-dialog>

    <!-- 驾驶人和随行人选择对话框 -->
    <UserSelector
      v-model:visible="userSelectVisible"
      :title="userSelectTitle"
      :selected-user-ids="currentSelectedUserIds"
      :selected-user-names="currentSelectedUserNames"
      :multiple="currentSelectField === 'entourage'" 
      @confirmWithIds="handleUserSelectWithIds"
      @cancel="handleUserSelectCancel"
    />

     <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        v-model:file-list="uploadRefFileList"
        accept=".jpg,.png,.jpeg,.gif"
        :headers="upload.headers"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-remove="handleFileRemove"
        :auto-upload="false"
        :multiple="true"
        drag
        list-type="picture"
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入.jpg, .png, .jepg, .PNG, .gif图片格式。</span>
            <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleImportTemplate"
              >下载模板</el-link
            > -->
          </div>
        </template>
      </el-upload>
      <!-- 文件列表 -->
      <div v-if="uploadRefFileList.length > 0" class="mt-4">
        <el-table :data="uploadRefFileList" size="small" border>
          <el-table-column prop="name" label="文件名" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button link type="primary" @click="handlePreview(scope.row)">预览</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 文件预览组件 -->
    <FilePreview v-model="preview.open"
                :url="preview.url"
                :title="preview.title"
                :type="preview.type" />

     <!-- 审核流程配置对话框 --> 
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'ADM-CAR-DRIVE-RECORD-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置车辆行驶记录审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="AdmCarDriveRecord" lang="ts">
import { getProContract } from '@/api/project/init/contract';
import { listAdmCarDriveRecord, getAdmCarDriveRecord, delAdmCarDriveRecord, batchAddRecords, batchUpdateRecords } from '@/api/general/administration/car/drive';
import { AdmCarDriveRecordVO, AdmCarDriveRecordQuery, AdmCarDriveRecordForm, Trip } from '@/api/general/administration/car/drive/types';
import { uploadAttachment, deleteUploadFile, queryApplyListByUser, queryAllByUser, getCarUseRecords } from '@/api/general/administration/car/apply';
import { queryCanInfo } from '@/api/general/administration/car/store';
import { AdmCarStoreDto } from '@/api/general/administration/car/store/types';
import { AdmCarApplyVO, AdmCarApplyQuery } from '@/api/general/administration/car/apply/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { globalHeaders } from '@/utils/request';
import { UploadQuery } from '@/api/general/administration/car/upload/types';
import { getProjectNamesByIds, pageListProInfo } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { any } from 'vue-types';
import { dayjs } from 'element-plus';
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';
import { pageListForQuery, getProInfo } from '@/api/project/init/proInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 全局配置
const BASE_URL = import.meta.env.VITE_APP_BASE_API || 'http://localhost:8080';
const admCarDriveRecordList = ref<AdmCarDriveRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 用户信息
const userStore = useUserStore();

const Listloading = ref(false);

// 判断是新增还是修改
const isNew = ref(false);

// 响应式表格数据
const applications = ref<Trip[]>([]);
// 表格选中
const selectedTrips = ref<Trip[]>([]);
// 编辑弹窗相关
const editingState = reactive(new Map<Trip, Record<string, boolean>>());
// 用来存储当前编辑的行
const currentRow = ref<Trip | null>(null);

// 初始化申请表
const applyList = ref<AdmCarApplyVO[]>([]);
const carList = ref<any[]>([]);

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);

// 驾驶人和随行人选择相关
const userSelectVisible = ref(false);
const userSelectTitle = ref('');
// 是否多选，根据字段判断
const isJoint = (field: 'usage' | 'entourage') => field === 'entourage';
const currentSelectedUserIds = ref('');
const currentSelectedUserNames = ref('');
const currentActualStage = ref<any>(null);
const currentSelectStageIndex = ref(-1);
// 当前选择字段：'usage' 或 'entourage'
const currentSelectField = ref<'usage' | 'entourage' | null>(null);

// 引入数据字典
const { car_type_options, approval_commit_status } = toRefs<any>(proxy?.useDict('car_type_options', 'approval_commit_status'));

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);
// 搜索关键词
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');
const projectLoading = ref(false);
const projectList = ref<ProInfoVO[]>([]);
// 防抖计时器
let projectSearchTimer: NodeJS.Timeout | null = null;
// 防止并发请求覆盖
let currentRequestId = 0;

// 导入相关
const uploadRef = ref<any>();
// 已上传文件，用于回显和 form.attachment
const uploadedFiles = ref<any[]>([]);
// 当前待上传文件列表
const uploadRefFileList = ref<any[]>([]);
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 上传的类型
  type: undefined,
  // 设置上传的请求头部
  headers: globalHeaders()
});
// 预览状态
const preview = reactive({
  open: false,
  url: "",
  title: "",
  type: "",
  rawFile: null
})

const currentItem = ref<any>(null) // 当前操作的 item

const itemFormRef = ref(new Map<string, ElFormInstance | null>())
function setItemFormRef(el: ElFormInstance | null, id: number | string) {
  const key = String(id)
  if (el) {
    itemFormRef.value.set(key, el)
  } else {
    itemFormRef.value.delete(key)
  }
}

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

const carTypeMap = {
  0: '私车',
  1: '公车',
  2: '租车'
};

const queryFormRef = ref<ElFormInstance>();
const admCarDriveRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

/**
 * 生成32位UUID
 * @returns string 32位UUID
 */
function generateUUID32(): string {
  // 生成标准 UUID v4，然后去掉 "-"
  return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, () =>
    ((Math.random() * 16) | 0).toString(16)
  );
}


const initFormData: AdmCarDriveRecordForm = {
  id: undefined,
  recordId: userStore.userId,
  recordName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  recordTime: formatLocalDate(),
  carApplyId: undefined,
  carReimburseId: undefined,
  applyVos: [] as AdmCarApplyVO[],
  // 申请表数据字段暂存
  startMileage: undefined, 
  carType: undefined,
  useId: userStore.userId,
  endMileage: undefined,
  mileageNumber: undefined,
  toll: undefined,
  fuelCost: undefined,
  oilConsumption: undefined,
  oilPrice: undefined,
  postageSubsidy: undefined,
  parkFree: undefined,
  rentalFree: undefined,
  maintenanceCost: undefined,
  otherExpenses: undefined,
  amountAll: undefined,
  attachmentId: undefined,
  attachmentName: undefined,
  remark: undefined,
  number: undefined,
  status: undefined,
  dateRange: undefined,
  carId: undefined,
  selected: undefined,
}
const data = reactive<PageData<AdmCarDriveRecordForm, AdmCarDriveRecordQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    carReimburseId: undefined,
    endMileage: undefined,
    mileageNumber: undefined,
    toll: undefined,
    fuelCost: undefined,
    oilConsumption: undefined,
    oilPrice: undefined,
    postageSubsidy: undefined,
    parkFree: undefined,
    rentalFree: undefined,
    maintenanceCost: undefined,
    otherExpenses: undefined,
    amountAll: undefined,
    attachmentId: undefined,
    number: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {}
});

// 动态图书表单校验规则（除了备注，其他都必填）



const { queryParams, form, rules } = toRefs(data);

/** 查询车辆行驶记录列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmCarDriveRecord(params);
    admCarDriveRecordList.value = res.rows;
    console.log('Fetched list:', admCarDriveRecordList.value);
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  // 重置表单
  reset();
  // 关闭弹窗
  dialog.visible = false;
  // 清空记录列表（可选，看需求是否保留）
  applications.value = [];
  // 清空上传组件状态
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
  upload.open = false;
  currentItem.value = null;
};

/** 删除按钮操作 */
const handleDelete = async (row?: AdmCarDriveRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除车辆行驶记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmCarDriveRecord(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 表单重置 */
const reset = () => {
  // 深拷贝，避免旧引用残留
  form.value = JSON.parse(JSON.stringify(initFormData));
  // 重置表单校验
  admCarDriveRecordFormRef.value?.resetFields();
  // 清空上传组件
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
  // 重置状态
  isNew.value = false;
  // 清空当前附件对象
  currentItem.value = null;
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加车辆行驶记录"; 
  // 同步到 currentItem
  currentItem.value = { ...form.value, _uploadedFiles: [] };
  console.log('新增表单 currentItem:', currentItem.value);
}

/** 修改按钮操作 */
const handleUpdate = async (row: any) => {
  try {
    if(row.status != 4){
      ElMessage.error('只能对审核不通过的信息进行修改！');
      return;
    }
    Listloading.value = true;
    reset();
    currentItem.value = row;
    console.log("当前操作的行驶记录", row);

    // 1. car 回显
    const carObj = { id: row.carId, carName: row.carName };
    Object.assign(form.value, {
      recordName: row.recordName || '',
      deptName: row.records?.[0]?.deptName || '',
      carId: carObj.id || '',
      carName: carObj.carName || '',
      dateRange: [
        row.minUseTime || row.list?.[0]?.useTime,
        row.maxBackTime || row.list?.[0]?.backTime
      ],
    });
    // 2. 项目回显
    if (row.list && Array.isArray(row.list)) {
      for (const item of row.list) {
        if (item.projectId) {
          const projectIds = item.projectId
            .toString()
            .split(',')
            .map(id => id.trim())
            .filter(Boolean);

          item.projectIds = projectIds; // 字符串数组，用于 el-select v-model

          try {
            const projRes = await getProjectNamesByIds(projectIds.join(','));
            item.projectName = projRes; // 拼接好的字符串，用于展示

            // 生成 projectList，给 el-select 回显用
            const nameArr = projRes.split(',').map(n => n.trim());
            item.projectList = projectIds.map((id, index) => ({
              id,
              proName: nameArr[index] || '',
              proNumber: '' // 如果后端有编号可以放这里
            }));
          } catch (err) {
            console.error('获取项目名称失败', err);
            item.projectName = '';
            item.projectList = [];
          }
        } else {
          item.projectIds = [];
          item.projectName = '';
          item.projectList = [];
        }
      }
    }

    // 3. 处理 list 数据
    applications.value = (row.list || []).map(item => {
      const usageTime = item.usageTime ? dayjs(item.usageTime).format('YYYY-MM-DD') : '';
      const useTime = item.useTime ? dayjs(item.useTime).format('YYYY-MM-DD') : '';
      const backTime = item.backTime ? dayjs(item.backTime).format('YYYY-MM-DD') : '';

      // 附件回显，生成 fileList 让组件能显示
      const fileList = item.attachmentId
        ? [{
            id: item.attachmentId,
            name: item.attachmentName || '',
            url: item.url || '',
            fullUrl: item.url || '',
            status: 'success',
            uid: Date.now() + Math.random()
          }]
        : [];

      // 随行人员回显
      const selectedEntourageIds = item.entourageId || '';
      const selectedEntourageNames = item.entourageName || '';

      // 报销时间
      const reimbursementTimeArr = (item.reimbursementTime || '').split(',').filter(Boolean);
      // 调用 loadAttachments 回显附件
      loadAttachments(item);

      return {
        ...item,
        useTime,
        backTime,
        usageTime,
        selectedEntourageIds,
        selectedEntourageNames,
        fileList,
        _uploadedFiles: fileList,
        attachmentName: fileList.map(f => f.name).join(','),
        reimbursementTime: reimbursementTimeArr,
        editing: {}
      };
    });

    console.log("回显的行程列表", applications.value);

    isNew.value = true;
    dialog.visible = true;
    dialog.title = '修改车辆行驶记录';
  } catch (err) {
    console.error("修改回显失败:", err);
    ElMessage.error('回显数据失败，请重试');
  } finally {
    Listloading.value = false;
  }
};



/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admCarDriveRecord/export', {
    ...queryParams.value
  }, `admCarDriveRecord_${new Date().getTime()}.xlsx`)
}


// 查询申请表中本次申请的数据
const getApplyData = async () => { 
  const param = {
    useId: userStore.userId,
    carId: form.value.carId
  };
  const res = await queryApplyListByUser(param);
  applyList.value = res.data;
  console.log("申请表数据", applyList.value);

   // 1. 收集所有 projectId
  const allProjectIds = applyList.value
    .filter(item => item.projectId)
    .flatMap(item => String(item.projectId).split(',').map(id => id.trim()));
  
  const uniqueProjectIds = Array.from(new Set(allProjectIds));

  let projectNamesMap: Record<string, string> = {};

  if (uniqueProjectIds.length > 0) {
    // 2. 调接口获取所有 projectId 对应的名称
    const projectRes = await getProjectNamesByIds(uniqueProjectIds.join(','));
    
    if (projectRes && typeof projectRes === 'object') {
      // 后端返回的是 map: { "1887": "项目A", "1890": "项目B" }
      projectNamesMap = projectRes;
    } else if (projectRes && typeof projectRes === 'string') {
      // 后端返回拼接字符串: "项目A,项目B,项目C"
      const namesArray = projectRes.split(',');
      uniqueProjectIds.forEach((id, index) => {
        projectNamesMap[id] = namesArray[index]?.trim() || '';
      });
    }
  }
  console.log("项目映射", projectNamesMap);
  // 映射成 Trip 类型并赋值到 applications
  applications.value = applyList.value.map((item: any) => {
    form.value.carApplyId = item.id;
    console.log("申请数据", item.projectId);
     // 处理 projectName
    const projectNames = item.projectId
      ? item.projectId
          .split(',')
          .map(id => projectNamesMap[id.trim()] || '')
          .filter(name => name)
          .join(', ')
      : '';
    const trip: Trip = {
      id: item.id,
      deptId: item.deptId,
      deptName: item.deptName,
      projectId: item.projectId,
      projectName: projectNames, // ✅ 回显项目名称
      carId: item.carId,
      carName: item.carName,
      carType: item.carType,
      usageId: item.useId,
      usageName: item.useName,
      departurePlace: item.departurePlace,
      destination: item.destination,
      useTime: dayjs(item.useTime).format('YYYY-MM-DD'),
      backTime: dayjs(item.backTime).format('YYYY-MM-DD'),
      startMileage: item.startMileage,
      driverName: item.driverName,
      entourageName: item.entourageName,
      attachmentName: item.attachmentName,
      number: item.number,
      remark: item.useReason,
      selectedUserIds: item.useId ? String(item.useId) : '',
      selectedUserNames: item.useName || '',
      selectedEntourageIds: item.entourageId || '',
      selectedEntourageNames: item.entourageName || '',
      reimbursementStatus: item.reimbursementStatus,
      readonly: true
    };
    return trip;
  });
  console.log("申请表数据", applications.value);
};



// 处理里程变化，传入当前 item
const handleMileageChange = (item) => {
  computeMileage(item)
}

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};


/**
 * 提交上传文件
 */
const submitFileForm = async () => {
  if (!currentItem.value) return;

  const files = uploadRefFileList.value.map(f => f.raw).filter(Boolean);
  if (!files.length) {
    ElMessage.warning('请先选择文件！');
    return;
  }

  upload.isUploading = true;
  try {
    await uploadAttachment(files, userStore.userId, currentItem.value.number, upload.type);
    await loadAttachments(currentItem.value); // 加载上传后的附件

    // 文件已经回显在 currentItem.value._uploadedFiles 中
    currentItem.value.attachmentId = currentItem.value._uploadedFiles.map(f => f.id).join(',');
    currentItem.value.attachmentName = currentItem.value._uploadedFiles.map(f => f.name).join(',');

    ElMessage.success('上传成功');
    uploadRefFileList.value = [];
    uploadRef.value?.clearFiles();
    upload.open = false;
  } catch (err) {
    console.error(err);
    ElMessage.error('上传失败，请重试');
  } finally {
    upload.isUploading = false;
  }
};



/**
 * 打开附件上传弹窗
 */
const handleAttachmentUpload = async (item: any, type: number) => {
  console.log("当前项:", item);
  currentItem.value = item;
  upload.type = type;
  upload.title = '附件信息上传';
  upload.open = true;

  // 回显已有附件
  uploadRefFileList.value = [...(item._uploadedFiles || [])];
  uploadRef.value?.clearFiles();

  if (item.number) {
    await loadAttachments(item);  // 加载已有附件
  }
  // 等 Vue 完成 DOM 更新后再给组件赋值
  nextTick(() => {
    uploadRefFileList.value = item._uploadedFiles ? [...item._uploadedFiles] : [];
  });
};


 // 页面初始化或表单加载完成后调用
const loadAttachments = async (item: any) => {
  if (!item.number || !userStore.userId) return;
  try {
    const query: UploadQuery = { number: item.number, uploadId: userStore.userId };
    const response = await queryAllByUser(query);
    console.log("附件查询结果:", response.data);
    const existingFiles = (response.data || []).map(f => ({
      id: f.id,
      name: f.name,
      url: getFileUrl(f.url) || '',
      fullUrl: getFileUrl(f.url),
      raw: null,
      status: 'success'
    }));
    // 挂载到当前 item
    item._uploadedFiles = existingFiles;
    // 上传组件绑定
    uploadRefFileList.value = [...existingFiles];
    // 同步到表单字段
    item.attachmentId = existingFiles.map(f => f.id).join(',');
    item.attachmentName = existingFiles.map(f => f.name).join(',');
    console.log('更新后的 item:', item);
  } catch (err) {
    console.error('附件加载失败', err);
    ElMessage.error('附件加载失败');
  }
}


// 取消上传
const cancelUpload = () => {
  upload.open = false;
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
};

// 获取完整 URL
const getFileUrl = (url: string) => {
  if (!url) return '';
  // 已经是完整路径就直接返回
  if (url.startsWith('http') || url.startsWith('file://')) return url;
  // 去掉前面的 '/upload'，然后拼接
  const fileName = url.substring(url.lastIndexOf('/') + 1); 
  return `${BASE_URL}upload/${fileName}`;
};

/**
 * 删除单个文件
 * @param file 当前删除的文件对象
 * @param index 文件在 file-list 中的索引
 */
const handleFileRemove = async (file: any) => {
  if (!currentItem.value) return;

  try {
    if (file.id) await deleteUploadFile(file.id);
    ElMessage.success(`${file.name} 已删除`);
    await loadAttachments(currentItem.value); // 刷新附件列表
  } catch (err) {
    console.error(err);
    ElMessage.error(`删除文件 ${file.name} 失败`);
  }
};

const validateApplications = (): string[] => {
  const errors: string[] = [];
  applications.value.forEach((row, index) => {
    const rowNum = index + 1;
    if (!row.projectId) {
      errors.push(`第 ${rowNum} 行项目不能为空`);
    }
    if (!row.usageName) {
      errors.push(`第 ${rowNum} 行使用人不能为空`);
    }
    if (!row.useTime) {
      errors.push(`第 ${rowNum} 行用车时间不能为空`);
    }
    if (!row.departurePlace) {
      errors.push(`第 ${rowNum} 行出发地点不能为空`);
    }
    if (!row.destination) {
      errors.push(`第 ${rowNum} 行目的地不能为空`);
    }
    if (row.startMileage == null) {
      errors.push(`第 ${rowNum} 行起始里程不能为空`);
    }
    if (row.endMileage == null) {
      errors.push(`第 ${rowNum} 行终止里程不能为空`);
    }
  });
  return errors;
};


/** 批量新增或修改 */
const submitAll = async () => {
  if (!applications.value.length) {
    ElMessage.warning('请至少添加一条记录后再提交');
    return;
  }
  if (!form.value) {
    ElMessage.error('表单未就绪，请稍后重试');
    return;
  }
  // 校验表格必填项
  const errors = validateApplications();
  if (errors.length > 0) {
    // 使用 ElMessageBox 显示所有错误
    ElMessageBox.alert(errors.join('\n'), '提示', { type: 'warning' });
    return;
  }
  // 格式化函数：处理 reimbursementTime
  const normalizeRecords = (records: any[]) =>
    records.map(({ id, reimbursementTime, recordId, ...rest }) => ({
      ...rest,
      // recordId 作为主键，id 仅作前端临时标识
      recordId: recordId || undefined,
      reimbursementTime: Array.isArray(reimbursementTime)
        ? reimbursementTime.join(',')
        : reimbursementTime || null,
      carId: form.value.carId,
      carApplyId: form.value.carApplyId,
    }));
  // 拆分新增与修改
  const newRecords = normalizeRecords(
    applications.value.filter(item => !item.recordId)
  );
  const updateRecords = normalizeRecords(
    applications.value.filter(item => item.recordId)
  );
  try {
    // 新增
    if (newRecords.length) {
      console.log('新增记录:', newRecords);
      const res = await batchAddRecords({
        ...form.value,
        records: newRecords
      });
      ElMessage.success('新增记录成功');
      // 触发审核流程配置对话框
      auditIdForApproval.value = res.data;
      approvalFlowVisible.value = true;
    }
    // 修改
    if (updateRecords.length) {
      console.log('修改记录:', updateRecords);
      await batchUpdateRecords({
        ...form.value,
        records: updateRecords
      });
      ElMessage.success('修改记录成功');
      // 调用重置审核流程接口
      await resetApprovalStatus('ADM-CAR-DRIVE-RECORD-AUDIT', Number(form.value.carReimburseId), '不可审核')
    }
    dialog.visible = false;
    await getList();
    applications.value = [];
  } catch (err) {
    console.error('批量提交失败:', err);
    ElMessage.error('操作失败，请重试');
  }
};

// 监听对话框关闭
watch(approvalFlowVisible, async (newVal, oldVal) => {
  if (oldVal && !newVal) {
    // 对话框从显示变成隐藏时刷新列表
    await getList();
  }
});


// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 获取车辆全部信息
const getCarList = async () => {
  try {
    const param: AdmCarStoreDto = {
      isLend: '0',
      status: 1,
      // 其他字段根据需要添加
    };
    const response = await queryCanInfo(param);
    carList.value = response.data || [];
  } catch (error) {
    console.error('获取车辆列表失败:', error);
    proxy?.$modal.msgError('获取车辆列表失败');
  }
};

// 当用户在输入框改了起始里程
const onStartMileageChange = (row: Trip, val: string) => {
  row.startMileage = Number(val) || 0;
  const state = editingState.get(row) || {};
  state.startMileage = false;
  editingState.set(row, state);
  computeMileage(row);
};

// 当用户改了终止里程
const onEndMileageChange = (row: Trip, val: string) => {
  row.endMileage = Number(val) || 0;
  const state = editingState.get(row) || {};
  state.endMileage = false;
  editingState.set(row, state);
  computeMileage(row);
};

// 里程计算（更健壮）
const computeMileage = (row: Trip) => {
  const s = row.startMileage == null ? null : Number(row.startMileage);
  const e = row.endMileage == null ? null : Number(row.endMileage);

  if (s == null || e == null || Number.isNaN(s) || Number.isNaN(e)) {
    // 若任一为空或非法，清空或保留 null（按你业务调整）
    row.mileageNumber = null;
    // 也可不触发金额计算
    computeAmountAll(row);
    return;
  }
  const diff = e - s;
  // 如果你要允许负数里程请修改这里；通常设为 0（或抛错）
  row.mileageNumber = diff >= 0 ? diff : 0;
  // 同步触发金额计算（如果金额和里程有关）
  computeAmountAll(row);
};

// 兜底：如果某些情况未触发 change，deep watch 会补算（不会频繁开销）
watch(applications, (newArr) => {
  newArr.forEach(r => computeMileage(r));
}, { deep: true });

// 总费用计算（示例）
const computeAmountAll = (row: Trip) => {
  const toll = Number(row.toll || 0);
  const fuel = Number(row.fuelCost || 0);
  const postage = Number(row.postageSubsidy || 0);
  const park = Number(row.parkFree || 0);
  const rental = Number(row.rentalFree || 0);
  const maintenance = Number(row.maintenanceCost || 0);
  const other = Number(row.otherExpenses || 0);
  row.amountAll = toll + fuel - postage + park + rental + maintenance + other;
};

// 行新增/删除
const addTrip = () => {
  applications.value.push({
    reimbursementStatus: 0,
    usageId: undefined,
    usageName: '',
    usageTime: '',
    departurePlace: '',
    destination: '',
    useTime: '',
    backTime: '',
    startMileage: 0,
    endMileage: 0,
    mileageNumber: 0,
    toll: 0,
    fuelCost: 0,
    oilConsumption: 0,
    oilPrice: 0,
    postageSubsidy: 0,
    parkFree: 0,
    rentalFree: 0,
    maintenanceCost: 0,
    otherExpenses: 0,
    amountAll: 0,
    entourageName: '',
    driverName: '',
    carName: '',
    carType: '',
    attachmentName: '',
    remark: '',
    number: generateUUID32(),
    selectedUserIds: '',
    selectedEntourageIds: '',
    selectedUserNames: '',
    selectedEntourageNames: '',
    readonly: false
  });
};

const removeSelectedTrips = () => {
  applications.value = applications.value.filter(trip => !selectedTrips.value.includes(trip));
  selectedTrips.value = [];
};

const handleSelectionChange = (val: Trip[]) => {
  selectedTrips.value = val;
};

// 打开选择框（通用）
const openUserSelector = (row: Trip, field: 'usage' | 'entourage') => {
  currentRow.value = row;
  currentSelectField.value = field;   // 标记当前选择的是使用人还是随行人员
  userSelectTitle.value = field === 'usage' ? '选择使用人' : '选择随行人员';
  
  if (field === 'usage') {
    currentSelectedUserIds.value = row.selectedUserIds || '';
    currentSelectedUserNames.value = row.selectedUserNames || '';
  } else {
    currentSelectedUserIds.value = row.selectedEntourageIds || '';
    currentSelectedUserNames.value = row.selectedEntourageNames || '';
  }
  userSelectVisible.value = true;
};

// 处理选择确认
const handleUserSelectWithIds = (data: { users: any[]; userIds: string; userNames: string }) => {
  if (!currentRow.value) return;
  if (currentSelectField.value === 'usage') {
    const u = data.users[0]; // 单选
    currentRow.value.usageId = u.userId;
    currentRow.value.usageName = u.userName;
    currentRow.value.selectedUserIds = u.userId;
    currentRow.value.selectedUserNames = u.userName;
  } else {
    currentRow.value.entourageName = data.userNames;
    currentRow.value.entourageId = data.userIds;
    currentRow.value.selectedEntourageIds = data.userIds;
    currentRow.value.selectedEntourageNames = data.userNames;
  }
  handleUserSelectCancel();
};


// 取消选择
const handleUserSelectCancel = () => {
  currentRow.value = null;
  currentSelectField.value = null;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
  userSelectVisible.value = false;
};
const onCarChange = (value: number) => {
  console.log('选中的车辆ID:', value);
  form.value.carId = value; // 手动赋值，如果v-model已绑定，这行可省略
  // 这里不要重置form.carId或其他属性
  getApplyData();
};

// 表格行远程搜索方法（和表单搜索类似，但每行独立）
const queryProjectListForRow = async (query: string, row: any) => {
  projectSearchKeyword.value = query;

  if (projectSearchTimer) clearTimeout(projectSearchTimer);

  projectSearchTimer = setTimeout(async () => {
    projectLoading.value = true;
    try {
      const res = await pageListForQuery({
        pageNum: 1,
        pageSize: 50,
        flowStatus: '3',
        proName: query || undefined
      });
      row.projectList = res.rows || [];    // 每行独立数据源
    } catch (err) {
      console.error('获取项目列表失败', err);
      row.projectList = [];
    } finally {
      projectLoading.value = false;
    }
  }, 300);
};

// 表格行多选回显和展示名称
const handleProjectChange = (row: any, selectedIds: number[]) => {
  row.projectIds = selectedIds;

  if (!row.projectList) return;

  const selectedProjects = row.projectList.filter(p => selectedIds.includes(p.id));
  row.projectNames = selectedProjects.map(p => `${p.proName} (${p.proNumber || ''})`).join(', ');
};


// 返回费用字段对应的中文标签
const getFeeLabel = (prop: string) => {
  const labels: Record<string, string> = {
    toll: '过路费(元)',
    fuelCost: '油费(元)',
    oilConsumption: '油耗(L/100km)',
    oilPrice: '油价(元/L)',
    postageSubsidy: '油费补贴(元)',
    parkFree: '停车费(元)',
    rentalFree: '租赁费(元)',
    maintenanceCost: '维修费(元)',
    otherExpenses: '其它费用(元)',
    useTime: '用车时间',
    backTime: '返回时间',
  };
  return labels[prop] || prop;
};

const formatNumberInput = (row: any, prop: string) => {
  let value = row[prop];

  // 替换非数字和小数点的字符
  value = value
    .toString()
    .replace(/[^\d.]/g, '')         // 删除非数字和小数点
    .replace(/^\./g, '')             // 开头不能是小数点
    .replace(/\.{2,}/g, '.')         // 连续小数点合并为一个
    .replace('.', '$#$')             // 占位替换第一个小数点
    .replace(/\./g, '')              // 删除其他小数点
    .replace('$#$', '.');            // 恢复第一个小数点

  // 保留两位小数
  if (value.includes('.')) {
    const [intPart, decimalPart] = value.split('.');
    value = intPart + '.' + decimalPart.slice(0, 2);
  }

  row[prop] = value === '' ? null : parseFloat(value);
};

const onUseTimeChange = (row: any) => {
  if (row.backTime && new Date(row.useTime) > new Date(row.backTime)) {
    ElMessage.error('用车时间不能晚于返回时间');
    row.useTime = ''; // 或恢复为原值
  }
};

const onBackTimeChange = (row: any) => {
  if (row.useTime && new Date(row.backTime) < new Date(row.useTime)) {
    ElMessage.error('返回时间不能早于用车时间');
    row.backTime = ''; // 或恢复为原值
  }
};

/**
 * 文件预览
 * @param row 
 */
const handlePreview = (row: any) => {
  const ext = row.name?.split(".").pop()?.toLowerCase();
  let type = "";
  if (["jpg", "jpeg", "png", "gif"].includes(ext)) type = "image";
  else if (ext === "pdf") type = "pdf";
  else if (ext === "doc") {
    ElMessage.warning("暂不支持旧版 .doc 格式，请转成 .docx");
    return;
  } else if (ext === "docx") type = "word";
  else if (["xls", "xlsx"].includes(ext)) type = "excel";
  else type = "other";
  // 如果是本地文件，row.raw 必须是真 File 对象
  const rawFile = row.raw instanceof File ? row.raw : null;
  const url = row.url || (rawFile ? URL.createObjectURL(rawFile) : "");
  preview.open = true;
  preview.url = url;
  preview.title = row.name;
  preview.type = type;
  preview.rawFile = rawFile; // 传给 FilePreview
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};

const mapReimbursementStatus = (status: number | string) => {
  switch (status) {
    case 0:
      return '未报销';
    case 2:
      return '未完全报销';
    case 1:
      return '已报销';
    default:
      return '未知';
  }
};

// 打开审批弹窗
const openApprovalFlow = (row?: AdmCarDriveRecordVO) => {
  if (row.status != 5){
    ElMessage.error('只能提交已导入的信息审批！');
    return;
  }
  auditIdForApproval.value = row.id;
  approvalFlowVisible.value = true;
};

onMounted(() => {
  getList();
  fetchDeptTree();
  getCarList();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}

.editable-cell {
  cursor: pointer;
  padding: 4px;
  min-height: 32px;
  display: flex;
  align-items: center;
}

.project-name-cell {
  display: block;
  width: 100%;
}

.text-ellipsis {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}

</style>